<template>
	<div class="v-input-code">
		<div class="input-box" :style="{ width: `${inputWidth * length + (length - 1) * 20}px`, height: `${inputHeight}px` }">
			<input
				v-for="(item, index) in length"
				:key="index"
				type="text"
				:class="['input-item', { 'input-focus': focusIndex === index }]"
				:maxlength="1"
				:placeholder="placeholder"
				@input="onInput(index, $event)"
				@focus="onFocus(index)"
				@blur="onBlur(index)"
				@keydown="onkeydown(index, $event)"
				:focus="inputFocus[index]"
				:blur="inputBlur[index]"
			/>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, inject } from 'vue';

const props = defineProps({
	value: {
		type: String,
		default: ''
	},
	length: {
		type: Number,
		default: 4
	},
	inputWidth: {
		type: Number,
		default: 30
	},
	inputHeight: {
		type: Number,
		default: 50
	},
	focus: {
		type: Boolean,
		default: false
	},
	placeholder: {
		type: String,
		default: ''
	}
});

const emit = defineEmits(['update:value', 'complete']);

const config = inject<any>('config');
const focusIndex = ref<number | null>(null);
const inputFocus = ref([]);
const inputBlur = ref([]);

onMounted(() => {
	inputFocus.value.length = props.length;
	inputBlur.value.length = props.length;
});

const onInput = (index: number, event: any) => {
	const value = event.detail.value;
	if (value) {
		if (index < props.length - 1) {
			console.log(index + 1);
			inputFocus.value[index + 1] = true;
		}
		updateModelValue(value, index);
	} else {
		updateModelValue('', index);
	}
};
const onkeydown = (index: number, event: any) => {
	if (event.code === 'Backspace') {
		inputFocus.value[index] = false;
		// inputFocus.value[index - 2] = false;
		// inputFocus.value[index - 2] = true;
	}
};

const onFocus = (index: number) => {
	focusIndex.value = index;
};

const onBlur = (index: number) => {
	if (focusIndex.value === index) {
		focusIndex.value = null;
	}
};

const updateModelValue = (value: string, index: number) => {
	const newValue = props.value.split('');
	newValue[index] = value;
	const joinedValue = newValue.join('');
	emit('update:value', joinedValue);
	if (joinedValue.length === props.length) {
		emit('complete');
	}
};

watch(
	() => props.focus,
	(newValue) => {
		if (newValue) {
			inputFocus.value[0].focus();
		}
	}
);
</script>

<style lang="scss" scoped>
.v-input-code {
	display: flex;
	justify-content: center;
	align-items: center;
}

.input-box {
	display: flex;
	justify-content: center;
	align-items: center;
}

.input-item {
	width: v-bind("inputWidth + 'rpx'");
	height: v-bind("inputHeight + 'rpx'");
	margin: 0 15rpx;
	padding: 0 15rpx;
	text-align: center;
	font-size: 16px;
	border-bottom: 4rpx solid v-bind("config.border.color");
	outline: none;
	transition: all 0.3s ease;
}

.input-item:focus {
	border-bottom: 4rpx solid v-bind("config.border.default");
}

.input-focus {
	border-bottom: 4rpx solid v-bind("config.border.default");
}
</style>
